package com.force.langchain4j.filesource;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Paths;

@Data
public class FileBaseLoader {

	private String suffix;
	private InputStream inputStream;

	private String absolutePath;

	public static Object load(final MultipartFile file) {
		FileBaseLoader fileBaseLoader = new FileBaseLoader();
		return fileBaseLoader.loader(file);
	}

	public static Object load(final File file) {
		FileBaseLoader fileBaseLoader = new FileBaseLoader();
		return fileBaseLoader.loader(file);
	}

	public static Object load(final String filePath) {
		FileBaseLoader fileBaseLoader = new FileBaseLoader();
		return fileBaseLoader.loader(Paths.get(filePath).toFile());
	}

	public Object loader(File file) {
		suffix = FileUtil.getSuffix(file);
		inputStream = FileUtil.getInputStream(file);
		TxtFileLoader txtFileLoader = new TxtFileLoader();
		absolutePath=file.getAbsolutePath();
		return txtFileLoader.getSourceContent(this);
	}

	@SneakyThrows
	public Object loader(MultipartFile file) {
		String originalFilename = file.getOriginalFilename();
		suffix = FileUtil.getSuffix(originalFilename);
		inputStream = file.getInputStream();
		ClassPathResource classPathResource = new ClassPathResource(file.getName());
		file.transferTo(new File(classPathResource.getAbsolutePath()));
		absolutePath=classPathResource.getAbsolutePath();
		TxtFileLoader txtFileLoader = new TxtFileLoader();
		return txtFileLoader.getSourceContent(this);
	}

}
